/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/4/27 23:53
 */
package org.mechanic.fund.shiro;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.mechanic.fund.domain.system.manager.Role;
import org.mechanic.fund.domain.system.manager.User;
import org.mechanic.fund.service.product.impl.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * 自定义的 Realm
 *
 * @author mechanic
 * @version 0.0.1
 */
//@Component
public class CustomRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(CustomRealm.class);

    @Autowired
    private UserService userService;

    public CustomRealm() {
        // 采用MD5加密
        //setCredentialsMatcher(new HashedCredentialsMatcher("md5"));
    }

    /**
     * 获取用户的角色以及权限资源
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("##################执行Shiro权限认证##################");
        //获取当前登录输入的用户名，等价于(String) principals.getPrimaryPrincipal();
        String account = (String) super.getAvailablePrincipal(principals);
        //到数据库查是否有此对象
        //TODO:这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        User user = this.userService.findByAccount(account);

        //把principals放session中 key=userId value=principals
        //SecurityUtils.getSubject().getSession().setAttribute(user.getId(), SecurityUtils.getSubject().getPrincipals());

        if (user == null) {
            return null;
        }
        //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //为Shiro赋予角色
        info.setRoles(user.getRolesName());
        //为Shiro赋予权限
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            info.addStringPermissions(role.getPermissionsName());
        }
        return info;
    }

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
      AuthenticationToken authenticationToken) throws AuthenticationException {
        //UsernamePasswordToken对象用来存放提交的登录信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        logger.info("验证当前Subject时获取到token为：" + ReflectionToStringBuilder.toString(
          token,
          ToStringStyle.MULTI_LINE_STYLE
        ));

        //查出是否有此用户
        User user = this.userService.findByAccount(token.getUsername());
        if (user == null) {
            return null;
        }
        //byte[] salt = Encodes.decodeHex(user.getSalt());
        //ShiroUser shiroUser=new ShiroUser(user.getId(), user.getLoginName(), user.getName());
        //设置用户session
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("user", user);
        // 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
        return new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(), getName());
    }
}
